package com.party.admin.web.controller.mall;

import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.mall.MallCategorySpec;
import com.party.core.model.mall.MallGoodsSpec;
import com.party.core.model.mall.MallSpec;
import com.party.core.model.mall.MallSpecValue;
import com.party.core.service.mall.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * @Author: Administrator.
 * @Description: 商城规格
 * @Date:Created in 2017/8/22 0022.
 */
@Controller
@RequestMapping("mall/spec")
public class MallSpecController {
    @Autowired
    private IMallCategorySpecService mallCategorySpecService;
    @Autowired
    private IMallSpecService mallSpecService;
    @Autowired
    private IMallSpecValueService mallSpecValueService;
    @Autowired
    private IMallGoodsSpecService mallGoodsSpecService;
    @Autowired
    private IMallGoodsService mallGoodsService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 分类对应规格
     *
     * @param categoryId
     * @return
     */
    @RequestMapping(value = "specDialog")
    public ModelAndView specDialog(String categoryId, String specIds, String type) {
        ModelAndView mv = new ModelAndView("mall/spec/specDialog");
        // 分类对应的规格
        List<MallCategorySpec> categorySpecs = mallCategorySpecService.findByCategory(categoryId.split(","));
        List<String> categorySpecIds = (List<String>) CollectionUtils.collect(categorySpecs, input -> {
            MallCategorySpec mallCategorySpec = (MallCategorySpec) input;
            return mallCategorySpec.getSpecId();
        });
        if (categorySpecIds.size() > 0) {
            List<MallSpec> specList = mallSpecService.batchList(new HashSet<>(categorySpecIds), new MallSpec(), null);
            mv.addObject("specList", specList);
        }
        if (StringUtils.isNotEmpty(specIds)) {
            String[] newSpecIds = specIds.split(",");
            mv.addObject("useSpecIds", newSpecIds);
        }
        mv.addObject("type", type);
        return mv;
    }

    /**
     * 添加规格
     *
     * @return
     */
    @RequestMapping("selectSpec")
    public ModelAndView selectSpec(String specIds, String type) {
        ModelAndView mv = new ModelAndView("mall/spec/specDialog");
        List<MallSpec> specList = mallSpecService.list(new MallSpec());
        mv.addObject("specList", specList);
        mv.addObject("type", type);
        if (StringUtils.isNotEmpty(specIds)) {
            String[] newSpecIds = specIds.split(",");
            mv.addObject("useSpecIds", newSpecIds);
        }
        return mv;
    }

    /**
     * 保存分类规格
     *
     * @param categoryId
     * @param specIds
     * @return
     */
    @ResponseBody
    @RequestMapping("saveCategorySpec")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveCategorySpec(String categoryId, String specIds) {
        if (StringUtils.isEmpty(categoryId)) {
            return AjaxResult.error("分类编号不能为空");
        }
        try {
            mallCategorySpecService.deleteByUnique(new MallCategorySpec(categoryId, ""));

            for (String id : specIds.split(",")) {
                MallCategorySpec categorySpec = new MallCategorySpec(categoryId, id);
                mallCategorySpecService.insert(categorySpec);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存分类规格失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("");
        }
    }

    /**
     * 删除分类规格
     *
     * @param categoryId
     * @param specId
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteCategorySpec")
    public AjaxResult deleteCategorySpec(String categoryId, String specId) {
        if (StringUtils.isEmpty(categoryId) || StringUtils.isEmpty(specId)) {
            return AjaxResult.error("分类或者规格不能为空");
        }
        try {
            Integer count = mallGoodsService.checkCategorySpec(specId, categoryId);
            if (count > 0) {
                return AjaxResult.error("已分配，不能移除");
            }
            mallCategorySpecService.deleteByUnique(new MallCategorySpec(categoryId, specId));
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除分类规格失败", e);
            return AjaxResult.error("");
        }
    }

    /**
     * 规格列表
     *
     * @param spec
     * @param page
     * @param commonInput
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list(MallSpec spec, Page page, CommonInput commonInput) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("mall/spec/specList");
        Map<String, Object> params = CommonInput.appendParams(commonInput);
        List<MallSpec> specList = mallSpecService.webListPage(spec, params, page);
        mv.addObject("list", specList);
        mv.addObject("page", page);
        mv.addObject("spec", spec);
        return mv;
    }

    /**
     * 规格保存
     *
     * @param spec
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public AjaxResult save(MallSpec spec, BindingResult result) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(description);
        }

        try {
            if (StringUtils.isEmpty(spec.getId())) {
                mallSpecService.insert(spec);
            } else {
                List<MallGoodsSpec> goodsSpecs = mallGoodsSpecService.findBySpecId(spec.getId());
                if (goodsSpecs.size() > 0) {
                    return AjaxResult.error("该规格已分配，不能修改");
                }
                mallSpecService.update(spec);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存规格异常", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("规格编号不能为空");
        }
        try {
            List<MallCategorySpec> mallCategorySpecs = mallCategorySpecService.findBySpec(id);
            if (mallCategorySpecs.size() > 0) {
                return AjaxResult.error("该规格已分配");
            }
            List<MallGoodsSpec> goodsSpecs = mallGoodsSpecService.findBySpecId(id);
            if (goodsSpecs.size() > 0) {
                return AjaxResult.error("该规格已分配给商品");
            }
            mallSpecService.delete(id);
            mallSpecValueService.deleteBySpecId(id);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("规格删除失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 新增/编辑
     *
     * @param id
     * @return
     */
    @RequestMapping("toForm")
    public ModelAndView toForm(String id) {
        ModelAndView mv = new ModelAndView("mall/spec/specForm");
        if (StringUtils.isNotEmpty(id)) {
            MallSpec mallSpec = mallSpecService.get(id);
            mv.addObject("mallSpec", mallSpec);
        }
        return mv;
    }

    /**
     * 根据规格id获取规格值
     *
     * @param specId
     * @return
     */
    @ResponseBody
    @RequestMapping("getSpecValueById")
    public AjaxResult getSpecValueById(String specId) {
        if (StringUtils.isEmpty(specId)) {
            return AjaxResult.error("规格id不能为空");
        }

        List<MallSpecValue> specValues = mallSpecValueService.list(new MallSpecValue(specId));
        return AjaxResult.success(specValues);
    }

    /**
     * 规格值列表
     *
     * @param specId 规格id
     * @param page   分页参数
     * @return
     */
    @RequestMapping("specValueList")
    public ModelAndView specValueList(String specId, Page page) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("mall/spec/specValueList");
        List<MallSpecValue> mallSpecValues = mallSpecValueService.listPage(new MallSpecValue(specId), page);
        mv.addObject("specValues", mallSpecValues);
        MallSpec mallSpec = mallSpecService.get(specId);
        mv.addObject("mallSpec", mallSpec);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 规格值新增/编辑
     *
     * @param id 规格值id
     * @return
     */
    @RequestMapping("specValueForm")
    public ModelAndView specValueForm(String id, String specId) {
        ModelAndView mv = new ModelAndView("mall/spec/specValueForm");
        if (StringUtils.isNotEmpty(id)) {
            MallSpecValue specValue = mallSpecValueService.get(id);
            mv.addObject("specValue", specValue);
        }
        mv.addObject("specId", specId);
        return mv;
    }

    /**
     * 规格值保存
     *
     * @param specValue 规格值
     * @return
     */
    @ResponseBody
    @RequestMapping("specValueSave")
    public AjaxResult specValueSave(MallSpecValue specValue) {
        if (StringUtils.isEmpty(specValue.getSpecId())) {
            return AjaxResult.error("规格id不能为空");
        }
        try {
            if (StringUtils.isEmpty(specValue.getId())) {
                mallSpecValueService.insert(specValue);
            } else {
                List<MallGoodsSpec> goodsSpecs = mallGoodsSpecService.findBySpecValueId(specValue.getId());
                if (goodsSpecs.size() > 0) {
                    return AjaxResult.error("规格值已分配，不能修改");
                }
                mallSpecValueService.update(specValue);
            }
            return AjaxResult.success("保存成功");
        } catch (Exception e) {
            logger.error("规格值保存失败", e);
            return AjaxResult.error("保存失败");
        }
    }

    @ResponseBody
    @RequestMapping("specValueDelete")
    public AjaxResult specValueDelete(String specValueId) {
        if (StringUtils.isEmpty(specValueId)) {
            return AjaxResult.error("规格值id不能为空");
        }
        List<MallGoodsSpec> goodsSpec = mallGoodsSpecService.findBySpecValueId(specValueId);
        if (goodsSpec.size() > 0) {
            return AjaxResult.error("规格值已分配给商品");
        }
        try {
            mallSpecValueService.delete(specValueId);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("规格值删除失败", e);
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 验证规格值是否存在
     *
     * @param value  规格值
     * @param id     规格值id
     * @param specId 规格id
     * @return
     */
    @ResponseBody
    @RequestMapping("verifyValue")
    public AjaxResult verifyValue(String value, String id, String specId) {
        if (StringUtils.isEmpty(specId)) {
            return AjaxResult.error("规格编号不能为空");
        }
        if (StringUtils.isEmpty(value)) {
            return AjaxResult.error("规格值不能为空");
        }
        List<MallSpecValue> mallSpecValues = mallSpecValueService.findByValue(new MallSpecValue(specId, value));
        if (mallSpecValues.size() > 0) {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error("规格值已存在");
            }
            boolean flag = false;
            for (MallSpecValue db : mallSpecValues) {
                if (db.getId().equals(id)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error("规格值已存在");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 验证规格名是否存在
     *
     * @param name
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("verifySpecName")
    public AjaxResult verifySpecName(String name, String id) {
        if (StringUtils.isEmpty(name)) {
            return AjaxResult.error("规格名不能为空");
        }
        List<MallSpec> mallSpecs = mallSpecService.findByName(name);
        if (mallSpecs.size() > 0) {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error("规格名已存在");
            }
            boolean flag = false;
            for (MallSpec db : mallSpecs) {
                if (db.getId().equals(id)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error("品牌名称已存在");
            }
        }
        return AjaxResult.success();
    }
}
